import { program } from 'commander';
import colors from 'colors/safe';

import Modules, { ExternalApps } from '../config/Modules';
import PathHelper from '../utils/PathHelper';
import Printer from '../utils/Printer';
import ExecuteHelper from '../utils/ExecuteHelper';

interface FetchCommandOptions {
  modules: string,
}

interface ProjectConfig {
  repository: string,
  branch: string,
}

const gitLabProjects: Record<string, ProjectConfig> = {
  [ExternalApps.CloudAudit]: { repository: 'git@gitlab.ctyun.cn:cns-frontend/cloud-audit.git', branch: 'develop' },
  [ExternalApps.EShield]: { repository: 'git@gitlab.ctyun.cn:wangjunqing/eshield_web.git', branch: 'refine-base' },
  [ExternalApps.LogsAudit]: { repository: 'git@gitlab.ctyun.cn:cns-frontend/logs-audit.git', branch: 'develop' },
};

export const commandFetch = (options: FetchCommandOptions) => {
  if (options.modules === 'all') {
    Object.keys(gitLabProjects).forEach((projectName) => {
      fetchOneApp(projectName);
    });
    return;
  }
  const modulesToFetch = options.modules.split(',').map((moduleString) => {
    const [moduleName, branch] = moduleString.split('@');
    return { moduleName, branch };
  });
  modulesToFetch.forEach((moduleToFetch) => fetchOneApp(moduleToFetch.moduleName, moduleToFetch.branch));
};

const fetchOneApp = (name: string, branch?: string) => {
  const project = gitLabProjects[name];
  if (Modules.isInternal(name)) {
    Printer.warn(`${name} 是内部子应用，无需单独拉取代码。`);
    return;
  }
  if (!project) {
    Printer.warn(`${name} 不是外部子应用，无法拉取代码。`);
    return;
  }
  try {
    ExecuteHelper.run(
      `git clone ${project.repository} -b ${branch || project.branch} ${name}`,
      { cwd: PathHelper.getPathRelativeToRoot('../app/subApps') },
    );
  } catch (error: any) {
    Printer.warn(error.message);
  }
};

export default program
  .command('fetch')
  .description('从 GitLab 拉取外部子应用代码')
  .option(
    '-m, --modules [modules-string]',
    `外部子应用的名字和代码所在分支拼接起来的字符串，有如下几种用法：
      ${colors.gray('-m')} ${colors.green('all')} # 拉取所有子应用的默认分支
      ${colors.gray('-m')} ${colors.green('eshield')} # 拉取 eshield 的默认分支
      ${colors.gray('-m')} ${colors.green('eshield@refine-base')} # 拉取 eshield 的 refine-base 分支
      ${colors.gray('-m')} ${colors.green('eshield@refine-base,logsAudit,cloudAudit@feat-staging')} # 拉取 eshield 的 refine-base 分支、logsAudit 的默认分支和 cloudAudit 的 feat-staging 分支
    `,
  )
  .action(commandFetch);
